package com.security.controller;

import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.CacheRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: TongRui乀
 * @Date: 2020/3/21 9:49
 * @description：
 */
@RestController
@RequestMapping("authentication")
public class SecurityController {

    /**
     *  session 中缓存的请求信息
     */
    private RequestCache requestCache = new HttpSessionRequestCache();

    /**
     *  处理重定向
     */
    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    /**
     *  根据请求的url  判断登录拦截时返回的时登录页面还是一个json数据
     * @param request
     * @return
     */
    @RequestMapping("loginHandler")
    public Map<String,String> loginHandler(HttpServletRequest request, HttpServletResponse response) throws IOException {

        // 获取请求的url
        SavedRequest savedRequest = requestCache.getRequest(request, response);

        if(savedRequest != null){
            String url = savedRequest.getRedirectUrl();
            // 判断url是否时页面
            if(url.endsWith(".html")){
                // 重定向
                redirectStrategy.sendRedirect(request,response,"/imooc-signIn.html");
            }
        }

        HashMap<String, String> map = new HashMap<>();

        map.put("code", "1000");
        map.put("message", "未登录，请求先登录认证！");

        return map;
    }

}
